from django.shortcuts import render

# Create your views here.
from rest_framework.views import APIView
from django.http import JsonResponse
from django.db.models import Count, Q
from datetime import datetime, timedelta
from allmodels.models import SysLog
from rest_framework.response import Response
from django.core.paginator import Paginator
from login.views import verify_token  # 假设已经有验证 token 的函数

class VisitTrendView(APIView):
    def get(self, request, *args, **kwargs):
        # 获取 Authorization 令牌
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)
        # 获取查询参数
        start_date_str = request.GET.get('startDate')
        end_date_str = request.GET.get('endDate')

        # 检查参数是否完整
        if not start_date_str or not end_date_str:
            return JsonResponse({
                'code': '10001',
                'msg': '开始时间和结束时间是必需的'
            }, status=400)

        try:
            start_date = datetime.strptime(start_date_str, '%Y-%m-%d')
            end_date = datetime.strptime(end_date_str, '%Y-%m-%d')
        except ValueError:
            return JsonResponse({
                'code': '10002',
                'msg': '日期格式错误，应为yyyy-MM-dd'
            }, status=400)

        # 查询符合日期范围内的日志
        logs = SysLog.objects.filter(create_time__range=[start_date, end_date], is_deleted=False)

        # 获取每天的访问量统计 (浏览量PV、访客数UV、IP数)
        date_range = [start_date + timedelta(days=i) for i in range((end_date - start_date).days + 1)]
        dates = [d.strftime('%Y-%m-%d') for d in date_range]
        pv_list = []
        uv_list = []
        ip_list = []

        for date in date_range:
            date_str = date.strftime('%Y-%m-%d')
            logs_on_date = logs.filter(create_time__date=date_str)

            # 浏览量（PV）: 日志记录数
            pv_count = logs_on_date.count()

            # 访客数（UV）: 按创建人ID去重的计数
            uv_count = logs_on_date.values('create_by').distinct().count()

            # IP数: 按IP地址去重的计数
            ip_count = logs_on_date.values('ip').distinct().count()

            pv_list.append(pv_count)
            uv_list.append(uv_count)
            ip_list.append(ip_count)

        # 返回JSON响应
        return JsonResponse({
            'code': '00000',
            'data': {
                'dates': dates,
                'pvList': pv_list,
                'uvList': uv_list,
                'ipList': ip_list
            },
            'msg': '一切ok'
        })





class VisitStatsView(APIView):
    def get(self, request, *args, **kwargs):
        # 获取 Authorization 令牌
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        # 获取今天的日期
        today = datetime.today().date()

        # 获取昨天的日期
        yesterday = today - timedelta(days=1)

        # 今日PV统计（浏览量）
        today_pv = SysLog.objects.filter(create_time__date=today, is_deleted=False).count()
        total_pv = SysLog.objects.filter(is_deleted=False).count()

        # 今日UV统计（访客数, 去重create_by）
        today_uv = SysLog.objects.filter(create_time__date=today, is_deleted=False).values('create_by').distinct().count()
        total_uv = SysLog.objects.filter(is_deleted=False).values('create_by').distinct().count()

        # 今日IP统计（IP数, 去重IP）
        today_ip = SysLog.objects.filter(create_time__date=today, is_deleted=False).values('ip').distinct().count()
        total_ip = SysLog.objects.filter(is_deleted=False).values('ip').distinct().count()

        # 计算昨天的PV/IP/UV（用于计算增长率）
        yesterday_pv = SysLog.objects.filter(create_time__date=yesterday, is_deleted=False).count()
        yesterday_uv = SysLog.objects.filter(create_time__date=yesterday, is_deleted=False).values('create_by').distinct().count()
        yesterday_ip = SysLog.objects.filter(create_time__date=yesterday, is_deleted=False).values('ip').distinct().count()

        # 计算增长率
        def calculate_growth_rate(today_value, yesterday_value):
            if yesterday_value == 0:
                return 0
            return round(((today_value - yesterday_value) / yesterday_value), 2)

        pv_growth_rate = calculate_growth_rate(today_pv, yesterday_pv)
        uv_growth_rate = calculate_growth_rate(today_uv, yesterday_uv)
        ip_growth_rate = calculate_growth_rate(today_ip, yesterday_ip)

        # 构造返回数据
        data = [
            {
                "type": "pv",
                "title": "浏览量",
                "todayCount": today_pv,
                "totalCount": total_pv,
                "growthRate": pv_growth_rate,
                "granularityLabel": "日"
            },
            {
                "type": "uv",
                "title": "访客数",
                "todayCount": today_uv,
                "totalCount": total_uv,
                "growthRate": uv_growth_rate,
                "granularityLabel": "日"
            },
            {
                "type": "ip",
                "title": "IP数",
                "todayCount": today_ip,
                "totalCount": total_ip,
                "growthRate": ip_growth_rate,
                "granularityLabel": "日"
            }
        ]

        # 返回JSON响应
        return JsonResponse({
            "code": "00000",
            "data": data,
            "msg": "一切ok"
        })


class LogPageView(APIView):
    def get(self, request, *args, **kwargs):
        # 获取 Authorization 令牌
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        # 获取请求参数
        keywords = request.GET.get('keywords', '')
        create_time_range = request.GET.get('createTime', '')
        page_num = int(request.GET.get('pageNum', 1))
        page_size = int(request.GET.get('pageSize', 10))

        # 构建查询条件
        filters = Q(is_deleted=False)

        if keywords:
            filters &= Q(content__icontains=keywords) | Q(request_uri__icontains=keywords) | Q(
                ip__icontains=keywords) | Q(browser__icontains=keywords) | Q(os__icontains=keywords)

        if create_time_range:
            try:
                start_time, end_time = create_time_range.split(',')
                start_time = datetime.strptime(start_time, '%Y-%m-%d')
                end_time = datetime.strptime(end_time, '%Y-%m-%d')
                filters &= Q(create_time__range=(start_time, end_time))
            except ValueError:
                return Response({"code": "40001", "msg": "日期格式错误"}, status=400)

        # 查询日志数据
        logs = SysLog.objects.filter(filters).order_by('-create_time')

        # 分页处理
        paginator = Paginator(logs, page_size)
        page = paginator.page(page_num)

        # 构造响应数据
        log_list = []
        for log in page.object_list:
            log_list.append({
                "id": log.id,
                "module": log.get_module_display(),
                "content": log.content,
                "requestUri": log.request_uri,
                "method": log.request_uri.split(' ')[0] if log.request_uri else "",  # 解析HTTP方法
                "ip": log.ip,
                "region": f"{log.province} {log.city}" if log.province or log.city else "",
                "browser": log.browser,
                "os": log.os,
                "executionTime": log.execution_time,
                "createBy": log.create_by,
                "createTime": log.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                "operator": "管理员"  # 假设默认操作者为管理员
            })

        response_data = {
            "code": "00000",
            "data": {
                "list": log_list,
                "total": paginator.count
            },
            "msg": "一切ok"
        }

        return Response(response_data)